package demos.fb.xmppchat.helper;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.packet.Message;

import java.util.Iterator;
import java.util.Map;

public class FBMessageListener implements MessageListener, Runnable {

    private final FBMessageListener fbml = this;
    private final XMPPConnection connection;
    private Map<String, RosterEntry> friends;

    public FBMessageListener(XMPPConnection connection) {
        this.connection = connection;
        new Thread(this).start();
    }

    public void setFriends(Map<String, RosterEntry> friends) {
        this.friends = friends;
    }

    public void processMessage(Chat chat, Message message) {
        System.out.println();
        final Iterator<Map.Entry<String, RosterEntry>> iterator = friends.entrySet().iterator();
        String key = null;
        RosterEntry entry = null;

        while (iterator.hasNext()) {
            Map.Entry<String, RosterEntry> pair = iterator.next();
            key = pair.getKey();
            entry = pair.getValue();

            if (entry.getUser().equalsIgnoreCase(chat.getParticipant()))
                break;
        }

        if (message != null && message.getBody() != null && entry != null) {
            System.out.printf("You've got new message from %s(%s) :%n", entry.getName(), key);
            System.out.println(message.getBody());
            System.out.print("Your choice [1-3]: ");
        }
    }

    public void run() {
        connection.getChatManager().addChatListener(
                (chat, createdLocally) -> {
                    if (!createdLocally) {
                        chat.addMessageListener(fbml);
                    }
                }
        );
    }
}